package com.jiepos.mpos.biz.service.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.InsParamLimitDao;
import com.jiepos.mpos.common.dao.InsServiceParamDao;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Ins_Param_LimitEntity;
import com.jiepos.mpos.common.entity.App_Ins_Service_ParamEntity;
import com.jiepos.mpos.common.entity.App_Service_InfEntity;
import com.jiepos.mpos.common.entity.App_Service_ParamEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 机构业务参数Service
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.service.service
 * @ClassName InsServiceParamService
 * @history
 * @UpdateRemark []
 * @since 2017/9/27
 */
@Service
public class InsServiceParamService extends BaseService{

    @Autowired
    private InsServiceParamDao insServiceParamDao;

    @Autowired
    private InsParamLimitDao insParamLimitDao;

    @Autowired
    private ServiceParamService serviceParamService;


    /**
     * 根据条件查询机构及业务列表
     * @param pagination
     * @param appServiceInfEntity
     * @param appInsInfEntity
     * @return
     */
    public Map findByCondition(HttpServletRequest request,Pagination pagination, App_Service_InfEntity appServiceInfEntity, App_Ins_InfEntity appInsInfEntity){

        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT R.INS_UUID || ':' || DBMS_RANDOM.STRING('a',20) AS UUID, ")
                .append("        I.INS_CD || '-' || I.INS_CN_NM AS INS_CD_NAME, ")
                .append("        S.SERVICE_NO || '-' || S.SERVICE_NAME AS SERVICE_NO_NAME")
                .append("   FROM (SELECT INS_UUID, SERVICE_UUID ")
                .append("           FROM T_APP_INS_SERVICE_PARAM WHERE REC_ST != '0' ")
                .append("          GROUP BY INS_UUID, SERVICE_UUID) R, ")
                .append("        "+ DBConstant.Table.T_APP_INS_INF+" I, ")
                .append("        "+DBConstant.Table.T_APP_SERVICE_INF+" S ")
                .append("  WHERE R.INS_UUID = I.INS_UUID ")
                .append("    AND R.SERVICE_UUID = S.SERVICE_UUID ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(appServiceInfEntity.getService_no())){
            sqlBuf.append("   AND S.SERVICE_NO LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_no()+"%");
        }
        if(!StringUtils.isBlank(appServiceInfEntity.getService_name())){
            sqlBuf.append("   AND S.SERVICE_NAME LIKE ? ");
            params.add("%"+appServiceInfEntity.getService_name()+"%");
        }
        if(!StringUtils.isBlank(appInsInfEntity.getIns_cd())){
            sqlBuf.append("   AND I.INS_CD like ? ");
            params.add("%"+appInsInfEntity.getIns_cd()+"%");
        }

        pagination.queryString = sqlBuf.toString();
        pagination = super.getDirectInsAuthSql(request, pagination, "R", null);
        //执行查询
        return insServiceParamDao.getPaginationMap(pagination,"R",params);
    }

    /**
     * 获取业务树(编辑)
     * @return
     */
    public List<Map<String, Object>> getServiceInfTreeEdit(String ins_uuid){
        StringBuffer sb = new StringBuffer();
        sb.append("select t1.service_uuid as \"id\",null as \"pId\",t1.service_no||'-'||t1.service_name as \"name\" from ");
        sb.append(DBConstant.Table.T_APP_SERVICE_INF).append(" t1 where 1=1 ");
        sb.append(" and t1.rec_st != '0' ");
        sb.append(" and t1.service_type in ('1','2','3','5') ");
        List<Map<String, Object>> serList = insServiceParamDao.queryForList(getOrderSql(sb.toString(), "t1"));

        StringBuffer serUuids = new StringBuffer();
        for(Map<String, Object> menu : serList){
            serUuids.append("'").append(menu.get("id")).append("'").append(",");
        }

        sb = new StringBuffer();
        sb.append("select service_param_uuid as \"id\",service_uuid as \"pId\",PARAM_NO ||'-'|| PARAM_NAME as \"name\",'p' as \"flag\" from ");
        sb.append(DBConstant.Table.T_APP_SERVICE_PARAM);
        sb.append(" WHERE service_uuid IN (").append(serUuids.substring(0, serUuids.length()-1)).append(")");
        List<Map<String, Object>> paramList = insServiceParamDao.queryForList(getOrderSql(sb.toString(), null));

        if(serList != null && !serList.isEmpty()){
            for(Map<String, Object> map : serList){
                map.put("open", true);
            }
        }
        //根据查询的uuid来刷新业务树选中状态
        List<String> setParamsPerIns = this.getSetParamsPerIns(ins_uuid);

        if(paramList != null && !paramList.isEmpty()){
            for(Map<String, Object> map : paramList){
                map.put("open", true);
                //判断是否需要勾选
                if(setParamsPerIns.contains(map.get("id").toString())){
                    map.put("checked",true);
                }
            }
        }
        serList.addAll(paramList);
        return serList;
    }


    /**
     * 保存机构业务参数及限额数据
     * @param map
     * @param appInsServiceParamEntity1 实名认证业务参数
     * @param appInsServiceParamEntity2 高级认证业务参数
     * @param appInsParamLimitEntity12 实名认证贷记卡限额
     * @param appInsParamLimitEntity11 实名认证借记卡限额
     * @param appInsParamLimitEntity22 高级认证贷记卡限额
     * @param appInsParamLimitEntity21 高级认证借记卡限额
     * @return
     */
    public String saveInsServiceParam(Map map,
                                      App_Ins_Service_ParamEntity appInsServiceParamEntity1,
                                      App_Ins_Service_ParamEntity appInsServiceParamEntity2,
                                      App_Ins_Param_LimitEntity appInsParamLimitEntity12,
                                      App_Ins_Param_LimitEntity appInsParamLimitEntity11,
                                      App_Ins_Param_LimitEntity appInsParamLimitEntity22,
                                      App_Ins_Param_LimitEntity appInsParamLimitEntity21){
        //保存参数数据
        //反向格式化时间
        this.reverseFormat(appInsServiceParamEntity1);
        appInsServiceParamEntity1.setCustom_level(SystemConstant.CUSTOM_LEVEL_1);
        this.saveParam(map,appInsServiceParamEntity1);
        //反向格式化时间
        this.reverseFormat(appInsServiceParamEntity2);
        appInsServiceParamEntity2.setCustom_level(SystemConstant.CUSTOM_LEVEL_2);
        this.saveParam(map,appInsServiceParamEntity2);
        //保存限额数据
        appInsParamLimitEntity12.setCustom_level(SystemConstant.CUSTOM_LEVEL_1);
        appInsParamLimitEntity12.setCrd_nature(SystemConstant.CRD_NATURE_2);
        this.saveLimit(map,appInsParamLimitEntity12);
        appInsParamLimitEntity11.setCustom_level(SystemConstant.CUSTOM_LEVEL_1);
        appInsParamLimitEntity11.setCrd_nature(SystemConstant.CRD_NATURE_1);
        this.saveLimit(map,appInsParamLimitEntity11);
        appInsParamLimitEntity22.setCustom_level(SystemConstant.CUSTOM_LEVEL_2);
        appInsParamLimitEntity22.setCrd_nature(SystemConstant.CRD_NATURE_2);
        this.saveLimit(map,appInsParamLimitEntity22);
        appInsParamLimitEntity21.setCustom_level(SystemConstant.CUSTOM_LEVEL_2);
        appInsParamLimitEntity21.setCrd_nature(SystemConstant.CRD_NATURE_1);
        this.saveLimit(map,appInsParamLimitEntity21);
        return SystemConstant.SUCCESS;
    }

    //保存业务参数设置信息
    private void saveParam(Map map,App_Ins_Service_ParamEntity entity){
        //查找是否存在uuid、业务参数、会员级别
       /*Long serviceParamUuid =  this.selectServiceParam(entity.getIns_uuid(),entity.getService_uuid(),entity.getService_param_uuid(),entity.getCustom_level());*/
        if (!StringUtils.isBlank(entity.getIns_param_uuid())) {
            //更新
            entity = (App_Ins_Service_ParamEntity) this.saveCommonData(entity,map,"update");
            List noChangeList = new ArrayList();
            noChangeList.add("ins_param_uuid");
            noChangeList.add("rec_crt_ts");
            insServiceParamDao.update(entity,noChangeList);
        }else{
            //新增
            entity = (App_Ins_Service_ParamEntity) this.saveCommonData(entity, map, null);
            entity.setIns_param_uuid(IDFactoryUtil.getUUID());
            insServiceParamDao.save(entity);
        }
    }

    //保存业务参数限额信息
    private void saveLimit(Map map,App_Ins_Param_LimitEntity entity){
        //查找是否存在uuid、业务参数、会员级别
        Long limitParamUuid =  this.selectLimitParam(entity.getIns_uuid(),entity.getService_uuid(),entity.getService_param_uuid(),entity.getCustom_level(),entity.getCrd_nature());
            //以是否有uuid来区分操作
          /*  if (!StringUtils.isBlank(entity.getIns_pur_limit_uuid())) {*/
          if(limitParamUuid != null){
                //更新
                entity = (App_Ins_Param_LimitEntity) this.saveCommonData(entity, map, "update");
                List noChangeList = new ArrayList();
                noChangeList.add("ins_pur_limit_uuid");
                noChangeList.add("rec_crt_ts");
                insParamLimitDao.update(entity, noChangeList);
            } else {
                //新增
                entity = (App_Ins_Param_LimitEntity) this.saveCommonData(entity, map, null);
                entity.setIns_pur_limit_uuid(IDFactoryUtil.getUUID());
                insParamLimitDao.save(entity);
        }
    }

    /**
     * (业务参数设置信息)
     * 根据机构编号、业务主键、业务参数主键，会员，
     * 查询，如果存在则更新记录，如果没有则新增
     * @param ins_uuid
     * @param service_uuid
     * @param custom_level
     * @return
     */
    private Long selectServiceParam(String ins_uuid,String service_uuid,String Service_Param_Uuid, String custom_level){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT T.rec_id  ")
                .append(" FROM "+ DBConstant.Table.T_APP_INS_SERVICE_PARAM+" T ")
                .append("   where t.ins_uuid = ? ")
                .append("  and t.service_uuid = ?  ")
                .append(" and t.Service_Param_Uuid = ? ")
                .append(" and t.custom_level = ? ")
                .append(" and t.rec_st = '1' ");
        List<App_Ins_Service_ParamEntity> serList = insServiceParamDao.queryForListByParam(sqlBuf.toString(), new Object[]{ins_uuid,service_uuid,Service_Param_Uuid,custom_level});
        if(!CollectionUtil.isEmpty(serList)){
            return serList.get(0).getRec_id();
        }
        return null;
    }
    /**
     * (限额信息)
     * 根据机构编号、业务主键、业务参数主键，会员，
     * 查询，如果存在则更新记录，如果没有则新增
     * @param ins_uuid
     * @param service_uuid
     * @param custom_level
     * @return
     */
    private Long selectLimitParam(String ins_uuid,String service_uuid,String Service_Param_Uuid, String custom_level,String crd_nature){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT T.rec_id  ")
                .append(" FROM "+ DBConstant.Table.T_APP_INS_PARAM_LIMIT+" T ")
                .append("   where t.ins_uuid = ? ")
                .append("  and t.service_uuid = ?  ")
                .append(" and t.Service_Param_Uuid = ? ")
                .append(" and t.custom_level = ? ")
                .append(" and t.crd_nature = ? ")
                .append(" and t.rec_st = '1' ");
        List<App_Ins_Param_LimitEntity> serList = insParamLimitDao.queryForListByParam(sqlBuf.toString(), new Object[]{ins_uuid,service_uuid,Service_Param_Uuid,custom_level,crd_nature});
        if(!CollectionUtil.isEmpty(serList)){
            return serList.get(0).getRec_id();
        }
        return null;
    }

    /**
     * 根据机构uuid得到该机构下已设置过的业务参数集合
     * @param ins_uuid
     * @return
     */
    private List<String> getSetParamsPerIns(String ins_uuid){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT DISTINCT SERVICE_PARAM_UUID ")
                .append("   FROM  "+ DBConstant.Table.T_APP_INS_SERVICE_PARAM)
                .append("  WHERE REC_ST !='0' ");
        //参数集合
        List<String> params = new ArrayList<>();
        if(!StringUtils.isBlank(ins_uuid)){
            sqlBuf.append("  AND INS_UUID = ? ");
            params.add(ins_uuid);
        }
        //查询哪些业务参数设置过
        List<Map> list = insServiceParamDao.queryForList(sqlBuf.toString(),params);
        if(list == null || list.size() == 0){
            return new ArrayList<>();
        }else{
            List<String> result = new ArrayList<>();
            for (Map map : list){
                result.add(map.get("SERVICE_PARAM_UUID").toString());
            }
            return result;
        }
    }

    /**
     * 加载业务参数设置数据
     * @param ins_uuid
     * @param service_uuid
     * @param service_param_uuid
     * @return
     */
    public Map<String,Object> getInsServiceParamDataByUUID(String ins_uuid,String service_uuid,String service_param_uuid){
        Map<String,Object> result = new HashMap<>();

        StringBuffer sqlBuf =  getInitSql("").append(", ");
        sqlBuf.append(" INS_PARAM_UUID, ")
                .append("        INS_UUID, ")
                .append("        SERVICE_UUID, ")
                .append("        SERVICE_PARAM_UUID, ")
                .append("        CUSTOM_LEVEL, ")
                .append("        BEGDATE, ")
                .append("        BEGTIME, ")
                .append("        ENDDATE, ")
                .append("        ENDTIME, ")
                .append("        DEBIT_MINFEE, ")
                .append("        DEBIT_RATE, ")
                .append("        DEBIT_MAXFEE, ")
                .append("        DEBIT_ATTACHFEE, ")
                .append("        CREDIT_MINFEE, ")
                .append("        CREDIT_RATE, ")
                .append("        CREDIT_MAXFEE, ")
                .append("        CREDIT_ATTACHFEE, ")
                .append("        DEFAULT_AMOUNT, ")
                .append("        MIN_AMOUNT, ")
                .append("        MAX_AMOUNT, ")
                .append("        REC_ID, ")
                .append("        REC_ST, ")
                .append("        LAST_OPER_IN ")
                .append("   FROM  "+ DBConstant.Table.T_APP_INS_SERVICE_PARAM)
                .append("   WHERE REC_ST!='0' ")
                .append("   AND INS_UUID = ? ")
                .append("   AND SERVICE_UUID = ? ")
                .append("   AND SERVICE_PARAM_UUID = ? ");
        List<App_Ins_Service_ParamEntity> appInsServiceParamEntities = insServiceParamDao.queryForListByParam(sqlBuf.toString(), ins_uuid, service_uuid, service_param_uuid);
        if(appInsServiceParamEntities != null && appInsServiceParamEntities.size() >0){
            for (App_Ins_Service_ParamEntity entity : appInsServiceParamEntities){
                if(SystemConstant.CUSTOM_LEVEL_1.equals(entity.getCustom_level())){
                    this.format(entity);
                    //appInsServiceParamEntity1 实名认证业务参数
                    result.put("appInsServiceParamEntity1",entity);
                }else if(SystemConstant.CUSTOM_LEVEL_2.equals(entity.getCustom_level())){
                    this.format(entity);
                    //appInsServiceParamEntity2 高级认证业务参数
                    result.put("appInsServiceParamEntity2",entity);
                }
            }
        }
        //限额数据
        StringBuffer sqlBuf2 =  getInitSql("").append(", ");
        sqlBuf2.append(" INS_PUR_LIMIT_UUID, ")
                .append("        INS_UUID, ")
                .append("        SERVICE_UUID, ")
                .append("        SERVICE_PARAM_UUID, ")
                .append("        CSTOMER_TYPE, ")
                .append("        CUSTOM_LEVEL, ")
                .append("        CRD_NATURE, ")
                .append("        CRD_MEDIUM, ")
                .append("        SIGNAL_MINAMT, ")
                .append("        SIGNAL_MAXAMT, ")
                .append("        SIGNAL_CARD_NUM, ")
                .append("        SIGNAL_CARD_AMT, ")
                .append("        DAY_NUM, ")
                .append("        DAY_AMT, ")
                .append("        SIGNAL_CARD_MON_NUM, ")
                .append("        SIGNAL_CARD_MON_AMT, ")
                .append("        MON_NUM, ")
                .append("        MON_AMT, ")
                .append("        SIGNAL_CARD_INTERVAL, ")
                .append("        REC_ID, ")
                .append("        REC_ST, ")
                .append("        LAST_OPER_IN ")
                .append("   FROM  "+ DBConstant.Table.T_APP_INS_PARAM_LIMIT)
                .append("  WHERE REC_ST != '0' ")
                .append("    AND INS_UUID = ? ")
                .append("    AND SERVICE_UUID = ? ")
                .append("    AND SERVICE_PARAM_UUID = ? ");
        List<App_Ins_Param_LimitEntity> appInsParamLimitEntities = insParamLimitDao.queryForListByParam(sqlBuf2.toString(), ins_uuid, service_uuid, service_param_uuid);
        if(appInsParamLimitEntities != null && appInsParamLimitEntities.size()>0){
            for (App_Ins_Param_LimitEntity entity : appInsParamLimitEntities){
                if(SystemConstant.CUSTOM_LEVEL_1.equals(entity.getCustom_level())){
                    if(SystemConstant.CRD_NATURE_1.equals(entity.getCrd_nature())){
                        //appInsParamLimitEntity11 实名认证借记卡限额
                        result.put("appInsParamLimitEntity11",entity);
                    }else if(SystemConstant.CRD_NATURE_2.equals(entity.getCrd_nature())){
                        //appInsParamLimitEntity12 实名认证贷记卡限额
                        result.put("appInsParamLimitEntity12",entity);
                    }
                }else if(SystemConstant.CUSTOM_LEVEL_2.equals(entity.getCustom_level())){
                    if(SystemConstant.CRD_NATURE_1.equals(entity.getCrd_nature())){
                        //appInsParamLimitEntity21 高级认证借记卡限额
                        result.put("appInsParamLimitEntity21",entity);
                    }else if(SystemConstant.CRD_NATURE_2.equals(entity.getCrd_nature())){
                        //appInsParamLimitEntity22 高级认证贷记卡限额
                        result.put("appInsParamLimitEntity22",entity);
                    }
                }
            }
        }
        return result;
    }

    /**
     * 格式化，数据库-->页面显示
     * @param entity
     */
    private void format(App_Ins_Service_ParamEntity entity){
        if(!StringUtils.isBlank(entity.getBegdate())){
            entity.setBegdate(DateUtil.toString(DateUtil.strToDate(entity.getBegdate(),"yyyyMMdd"),"yyyy-MM-dd"));
        }
        if(!StringUtils.isBlank(entity.getBegtime())){
            entity.setBegtime(DateUtil.toString(DateUtil.strToDate(entity.getBegtime(),"HHmmss"),"HH:mm:ss"));
        }
        if(!StringUtils.isBlank(entity.getEnddate())){
            entity.setEnddate(DateUtil.toString(DateUtil.strToDate(entity.getEnddate(),"yyyyMMdd"),"yyyy-MM-dd"));
        }
        if(!StringUtils.isBlank(entity.getEndtime())){
            entity.setEndtime(DateUtil.toString(DateUtil.strToDate(entity.getEndtime(),"HHmmss"),"HH:mm:ss"));
        }
    }

    /**
     * 反向格式化 页面显示-->数据库
     * @param entity
     */
    private void reverseFormat(App_Ins_Service_ParamEntity entity){
        //时期及时间处理
        entity.setBegdate(DateUtil.toString(DateUtil.strToDate(entity.getBegdate(),"yyyy-MM-dd"),"yyyyMMdd"));
        entity.setBegtime(DateUtil.toString(DateUtil.strToDate(entity.getBegtime(),"HH:mm:ss"),"HHmmss"));
        entity.setEnddate(DateUtil.toString(DateUtil.strToDate(entity.getEnddate(),"yyyy-MM-dd"),"yyyyMMdd"));
        entity.setEndtime(DateUtil.toString(DateUtil.strToDate(entity.getEndtime(),"HH:mm:ss"),"HHmmss"));
    }

    /**
     * 刷新业务树
     * @param ins_uuid
     * @param service_param_uuids
     * @return
     */
    public String updateInsParamSetTree(String ins_uuid,String service_param_uuids,Map loginUser){
        //1.删掉库里面的差集
        //更新参数
        insServiceParamDao.deleteRecord(ins_uuid,service_param_uuids,String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
        //更新限额
        insParamLimitDao.deleteRecord(ins_uuid,service_param_uuids,String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
        //2.增补数据入库
        if(!StringUtils.isBlank(service_param_uuids)){
            //得到设置过的业务参数uuid结合
            List<String> savedList = getSetParamsPerIns(ins_uuid);
            //页面传过来的集合
            List<String> transList = Arrays.asList(service_param_uuids.split(","));
            //求传参过来的和现在库里的差集
            Collection<String> subtract = CollectionUtils.subtract(transList, savedList);
            if(subtract != null && subtract.size() > 0){
                for (String service_param_uuid : subtract){
                    App_Service_ParamEntity serviceParamEntity = serviceParamService.findByUUID(service_param_uuid);
                    if(serviceParamEntity != null){
                        //业务uuid
                        String service_uuid = serviceParamEntity.getService_uuid();
                        //保存参数数据
                        App_Ins_Service_ParamEntity appInsServiceParamEntity1 = this.initServiceParamEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_1);
                        this.saveParam(loginUser,appInsServiceParamEntity1);
                        App_Ins_Service_ParamEntity appInsServiceParamEntity2 = this.initServiceParamEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_2);
                        this.saveParam(loginUser,appInsServiceParamEntity2);
                        //保存限额数据
                        App_Ins_Param_LimitEntity appInsParamLimitEntity12 = this.initServiceParamLimitEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_1,SystemConstant.CRD_NATURE_2);
                        this.saveLimit(loginUser,appInsParamLimitEntity12);
                        App_Ins_Param_LimitEntity appInsParamLimitEntity11 = this.initServiceParamLimitEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_1,SystemConstant.CRD_NATURE_1);
                        this.saveLimit(loginUser,appInsParamLimitEntity11);
                        App_Ins_Param_LimitEntity appInsParamLimitEntity22 = this.initServiceParamLimitEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_2,SystemConstant.CRD_NATURE_2);
                        this.saveLimit(loginUser,appInsParamLimitEntity22);
                        App_Ins_Param_LimitEntity appInsParamLimitEntity21 = this.initServiceParamLimitEntity(ins_uuid,service_uuid,service_param_uuid,SystemConstant.CUSTOM_LEVEL_2,SystemConstant.CRD_NATURE_1);
                        this.saveLimit(loginUser,appInsParamLimitEntity21);
                    }
                }
            }
        }
        return SystemConstant.SUCCESS;
    }

    /**
     * 初始化机构业务参数数据
     * @param ins_uuid
     * @param service_uuid
     * @param service_param_uuid
     * @param custom_level
     * @return
     */
    public App_Ins_Service_ParamEntity initServiceParamEntity(String ins_uuid,String service_uuid,String service_param_uuid,String custom_level) {
        App_Ins_Service_ParamEntity entity = new App_Ins_Service_ParamEntity();
        entity.setIns_uuid(ins_uuid);
        entity.setService_uuid(service_uuid);
        entity.setService_param_uuid(service_param_uuid);
        entity.setCustom_level(custom_level);
        //
        Double zero = new Double(0);
        entity.setDebit_rate(zero);
        entity.setDebit_attachfee(zero);
        entity.setDebit_minfee(zero);
        entity.setDebit_maxfee(zero);
        entity.setCredit_rate(zero);
        entity.setCredit_attachfee(zero);
        entity.setCredit_minfee(zero);
        entity.setCredit_maxfee(zero);
        entity.setDefault_amount(zero);
        entity.setMin_amount(zero);
        entity.setMax_amount(zero);
        return entity;
    }

    /**
     * 初始化机构业务参数限额数据
     * @param ins_uuid
     * @param service_uuid
     * @param service_param_uuid
     * @param custom_level
     * @param crd_nature
     * @return
     */
    public App_Ins_Param_LimitEntity initServiceParamLimitEntity(String ins_uuid,String service_uuid,String service_param_uuid,String custom_level,String crd_nature){
        App_Ins_Param_LimitEntity entity = new App_Ins_Param_LimitEntity();
        entity.setIns_uuid(ins_uuid);
        entity.setService_uuid(service_uuid);
        entity.setService_param_uuid(service_param_uuid);
        entity.setCustom_level(custom_level);
        entity.setCrd_nature(crd_nature);
        //
        Double zero = new Double(0);
        Integer count = new Integer(0);
        entity.setSignal_minamt(zero);
        entity.setSignal_maxamt(zero);
        entity.setSignal_card_amt(zero);
        entity.setSignal_card_num(count);
        entity.setDay_num(count);
        entity.setDay_amt(zero);
        entity.setSignal_card_mon_num(count);
        entity.setSignal_card_mon_amt(zero);
        entity.setMon_amt(zero);
        entity.setMon_num(count);
        entity.setSignal_card_interval(count);
        return entity;
    }

    /**
     * 校验机构业务参数设置值是否有效
     * @param serviceParam
     * @param insServiceParam
     * @return
     */
    public List<String> checkInsParam(App_Service_ParamEntity serviceParam,App_Ins_Service_ParamEntity insServiceParam){
        List<String> result = new ArrayList<>();
        Double zero = new Double(0);
        //借记卡校验
        if(insServiceParam.getDebit_rate() != null && serviceParam.getMin_rate() != null && zero.compareTo(insServiceParam.getDebit_rate()) != 0
                && insServiceParam.getDebit_rate().doubleValue() < serviceParam.getMin_rate().doubleValue()){
            result.add("借记卡扣率");
        }
        if(insServiceParam.getDebit_attachfee() != null && serviceParam.getMin_attachfee() !=null && zero.compareTo(insServiceParam.getDebit_attachfee()) != 0
                && insServiceParam.getDebit_attachfee().doubleValue() <  serviceParam.getMin_attachfee().doubleValue()){
            result.add("借记卡附加手续费");
        }
        if(insServiceParam.getDebit_minfee() !=null && serviceParam.getMin_fee() != null && zero.compareTo(insServiceParam.getDebit_minfee()) != 0
                && insServiceParam.getDebit_minfee().doubleValue() < serviceParam.getMin_fee().doubleValue()){
            result.add("借记卡最小手续费");
        }
        if(insServiceParam.getDebit_maxfee() != null && serviceParam.getMin_maxfee()!=null && zero.compareTo(insServiceParam.getDebit_maxfee()) != 0
                && insServiceParam.getDebit_maxfee().doubleValue() < serviceParam.getMin_maxfee().doubleValue()){
            result.add("借记卡最大手续费");
        }
        //贷记卡校验
        if(insServiceParam.getCredit_rate() != null && serviceParam.getMin_rate2() != null && zero.compareTo(insServiceParam.getCredit_rate()) != 0
                && insServiceParam.getCredit_rate().doubleValue() < serviceParam.getMin_rate2().doubleValue()){
            result.add("贷记卡扣率");
        }
        if(insServiceParam.getCredit_attachfee() != null && serviceParam.getMin_attachfee2() !=null && zero.compareTo(insServiceParam.getCredit_attachfee()) != 0
                && insServiceParam.getCredit_attachfee().doubleValue() <  serviceParam.getMin_attachfee2().doubleValue()){
            result.add("贷记卡附加手续费");
        }
        if(insServiceParam.getCredit_minfee() !=null && serviceParam.getMin_fee2() != null && zero.compareTo(insServiceParam.getCredit_minfee()) != 0
                && insServiceParam.getCredit_minfee().doubleValue() < serviceParam.getMin_fee2().doubleValue()){
            result.add("贷记卡最小手续费");
        }
        if(insServiceParam.getCredit_maxfee() != null && serviceParam.getMin_maxfee2()!=null && zero.compareTo(insServiceParam.getCredit_maxfee()) != 0
                && insServiceParam.getCredit_maxfee().doubleValue() < serviceParam.getMin_maxfee2().doubleValue()){
            result.add("贷记卡最大手续费");
        }
        return result;
    }

    /**
     * 根据机构UUID和会员级别获取机构参数列表 For App
     * @param ins_uuid
     * @param custom_level
     * @return
     */
    public List<Map<String,Object>> getInsParamListByInsUUIDAndCustomLevel(String ins_uuid,String custom_level){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT B.SERVICE_UUID,B.SERVICE_NO AS \"service_no\",B.SERVICE_NAME AS \"service_name\",B.SERVICE_TYPE AS \"service_type\" FROM  ")
                .append(" ( ")
                .append("   SELECT SERVICE_UUID FROM T_APP_INS_SERVICE_PARAM ")
                .append("          WHERE INS_UUID = ? ")
                .append("            AND REC_ST != '0' ")
                .append("            AND CUSTOM_LEVEL = ? ")
                .append("            GROUP BY SERVICE_UUID ")
                .append(" ) A LEFT JOIN T_APP_SERVICE_INF B ")
                .append(" ON A.SERVICE_UUID = B.SERVICE_UUID ");
        List<String> params = new ArrayList<>();
        params.add(ins_uuid);
        params.add(custom_level);
        List<Map<String,Object>> serviceList = insParamLimitDao.queryForList(sqlBuf.toString(), params);
        if(serviceList != null && serviceList.size()>0){
            StringBuffer sqlBuf2 = new StringBuffer();
            sqlBuf2.append(" SELECT  P.PARAM_NO as \"param_no\", ")
                    .append("                P.PARAM_NAME as \"param_name\", ")
                    .append("                I.BEGDATE as \"begdate\", ")
                    .append("                I.BEGTIME as \"begtime\", ")
                    .append("                I.ENDDATE as \"enddate\", ")
                    .append("                I.ENDTIME as \"endtime\", ")
                    .append("                TO_CHAR(NVL(I.DEFAULT_AMOUNT , 0.00),'fm9999999990.00') as \"default_amount\", ")
                    .append("                TO_CHAR(NVL(I.MIN_AMOUNT , 0.00),'fm9999999990.00') as \"min_amount\", ")
                    .append("                TO_CHAR(NVL(I.MAX_AMOUNT , 0.00),'fm9999999990.00') as \"max_amount\", ")
                    .append("                TO_CHAR(NVL(I.debit_minfee , 0.00) * 100, 'fm9999999990') as \"debit_minfee\", ")
                    .append("                TO_CHAR(NVL(I.debit_rate , 0.00) * 100, 'fm9999999990') as \"debit_rate\", ")
                    .append("                TO_CHAR(NVL(I.debit_maxfee , 0.00) * 100, 'fm9999999990') as \"debit_maxfee\", ")
                    .append("                TO_CHAR(NVL(I.debit_attachfee , 0.00) * 100, 'fm9999999990') as \"debit_attachfee\", ")
                    .append("                TO_CHAR(NVL(I.credit_minfee , 0.00) * 100, 'fm9999999990') as \"credit_minfee\", ")
                    .append("                TO_CHAR(NVL(I.credit_rate , 0.00) * 100, 'fm9999999990') as \"credit_rate\", ")
                    .append("                TO_CHAR(NVL(I.credit_maxfee , 0.00) * 100, 'fm9999999990') as \"credit_maxfee\", ")
                    .append("                TO_CHAR(NVL(I.credit_attachfee , 0.00) * 100, 'fm9999999990') as \"credit_attachfee\" ")
                    .append("           FROM (SELECT * ")
                    .append("                   FROM T_APP_INS_SERVICE_PARAM ")
                    .append("                  WHERE INS_UUID = ? ")
                    .append("                    AND REC_ST != '0' ")
                    .append("                    AND CUSTOM_LEVEL = ? ")
                    .append("                    AND SERVICE_UUID = ?) I ")
                    .append("           LEFT JOIN T_APP_SERVICE_PARAM P ")
                    .append("             ON I.SERVICE_PARAM_UUID = P.SERVICE_PARAM_UUID ");
            for (Map<String,Object> service : serviceList){
                String service_uuid = service.get("SERVICE_UUID").toString();
                params.clear();
                params.add(ins_uuid);
                params.add(custom_level);
                params.add(service_uuid);
                List serviceParams = insParamLimitDao.queryForList(sqlBuf2.toString(), params);
                service.put("service_param_list",serviceParams);
                service.remove("SERVICE_UUID");
            }
        }
        return serviceList;
    }
}
